const { Transform } = require('stream');
const utils = require('../../utils');

module.exports = async function ({ user, password, server, database, table, sql, count = 1 }) {
  const mssql = require('mssql');
  await mssql.connect({
    user,
    password,
    server,
    database,
    requestTimeout: 120000,
    options: {
      enableArithAbort: true,
      encrypt: false,
    }
  });
  const db = new mssql.Request();
  db.stream = true;
  db.query(sql || `select top ${count} * from ${table}`);

  const stream = new Transform({ objectMode: true });
  db.on('row', async (row) => {
    stream.push(row);
  });
  db.on('done', async () => {
    stream.push(null);
  });
  stream.on('end', () => {
    mssql.close();
    utils.debug('sqlserverReader [end]');
  });
  return stream;
}
